package com.github.pig.common.util;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>
 * 驼峰转下划线 key
 * </p>
 * @Author: Carlos
 * @Date:2018/11/11 - 4:52 PM
 */
public class ConvertMapUtil {

    public static final char UNDERLINE='_';

    public static Map<String,Object> convertMapOfUnderLine(Map<String,Object> param){
        Map newParam = new LinkedHashMap();
        param.entrySet().forEach(o->newParam.put(camelToUnderline(o.getKey()),o.getValue()));
        return  newParam;
    }

    public static String camelToUnderline(String param){
        if (param==null||"".equals(param.trim())){
            return "";
        }
        int len=param.length();
        StringBuilder sb=new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c=param.charAt(i);
            if (Character.isUpperCase(c)){
                sb.append(UNDERLINE);
                sb.append(Character.toLowerCase(c));
            }else{
                sb.append(c);
            }
        }
        return sb.toString();
    }



    public static String underlineToCamel(String param){
        if (param==null||"".equals(param.trim())){
            return "";
        }
        int len=param.length();
        StringBuilder sb=new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c=param.charAt(i);
            if (c==UNDERLINE){
                if (++i<len){
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }
            }else{
                sb.append(c);
            }
        }
        return sb.toString();
    }


}
